<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-6-8
 * Time: 16:29
 */

namespace app\web\controller;

use app\common\builder\ZBuilder;
use app\common\controller\Alisms;
use app\common\controller\Api;
use app\common\model\Factor;
use app\common\model\Fenorder;
use app\common\model\SmsRecharge as SmsRechargeM;
use app\common\model\SmsRechargeLog as SmsRechargeLogM;
use app\common\model\SmsSign as SmsSignM;
use app\common\model\Store;
use app\common\controller\Smscm;
use think\Db;

/**
 * 前台首页控制器
 * @package app\index\controller
 */
class SendSms extends Auth
{
    public $noNeedLogin = ['register_send'];


    /**
     * 注册发送手机验证码
     */
    public function register_send()
    {
        if ($this->request->isPost()) {
            $getPhone = $this->request->post('phone');
            $type = $this->request->post('type');
            if (empty($getPhone)) {
                $this->result('请填写手机号', '', 204);
            }
            if (empty($type)) {
                $this->result('缺少类型', '', 204);
            }
            $storeId = $this->request->post('store_id');
            if (!isset($storeId) || empty($storeId)) {
                if(isset($this->userInfo['store_id'])){
                    $storeId = $this->userInfo['store_id'];
                }else{
                    $storeId = 0;
                }
            }
            if (preg_match("/^1[345786]\d{9}$/", $getPhone)) {
                $sms = new Alisms();
                //$code  = $sms->sms_rand();
                $code = 123456;
                //注册短信
                if ($type == 1) {
                    $content = "尊敬的用户，您的验证码是" . $code."请勿泄露于他人";
                    $res = $sms->sendsms($getPhone, $content, '1', $code,$storeId);
                } elseif ($type == 2) {
                    $content = "尊敬的用户，您的验证码是" . $code . '验证码只能用户找回密码';
                    $res = $sms->sendsms($getPhone, $content, '2', $code,$storeId);
                } elseif ($type == 3) {
                    $content = "尊敬的用户，您的验证码是" . $code;
                    $res = $sms->sendsms($getPhone, $content, '3', $code,$storeId);
                } else {
                    $this->result('无效的请求', '', 204);
                }
                if ($res == true) {
                    $this->result('短信发送成功', '', 200);
                }
                $this->result('短信发送失败', '', 204);
            }
            $this->result('请填写正确的手机号', '', 204);
        }
    }

    /**
     * 短信充值模板
     */
    public function recharge_list()
    {
        if ($this->request->isPost()) {
            $result = Db::name('qt_sms_recharge')->order('sort asc id desc')->select();
            $this->result('查询成功', $result, 200);
        }
    }


    /**
     * 短信充值模板
     */
    public function log_list()
    {
        // 读取数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (empty($data['page']) || empty($data['limit'])) {
                $this->result('缺少参数', '', 204);
            }
            $data_list = Db::name('qt_sms_recharge_log')->where('store_id', $this->userInfo['store_id'])
                ->field('l.*,s.name')
                ->alias('l')
                ->leftJoin('qt_store s', 's.id = l.store_id')
                ->order('id desc')
                ->paginate();
            $this->result('查询成功', $data_list, 200);
        }
    }


    /**
     * 短信发送记录
     */
    public function send_log_list()
    {
        // 读取数据
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (empty($data['page']) || empty($data['limit'])) {
                $this->result('缺少参数', '', 204);
            }
            $sql = Db::name('qt_sms')->where('store_id', $this->userInfo['store_id'])
                ->field('l.*,s.name')
                ->alias('l')
                ->leftJoin('qt_store s', 's.id = l.store_id')
                ->order('id desc');
            if (isset($data['start_time']) && !empty($data['start_time'])) {

                $start = strtotime($data['start_time']);
            }
            if (isset($data['end_time']) && !empty($data['end_time'])) {
                $end = strtotime($data['end_time']);
                $sql = Db::name('qt_sms')->where('store_id', $this->userInfo['store_id'])
                    ->field('l.*,s.name')
                    ->alias('l')
                    ->leftJoin('qt_store s', 's.id = l.store_id')
                    ->order('id desc')->whereBetweenTime('l.create_time', $start, $end);
            }
            $data_list = $sql->paginate();
            $this->result('查询成功', $data_list, 200);
        }
    }


    //编辑充值模板
    public function log_edit($id = null)
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            // 验证
            if (SmsRechargeLogM::update($data)) {
                $this->result('编辑成功', '', 200);
            } else {
                $this->result('编辑失败', '', 204);
            }
        } else {
            $info = SmsRechargeLogM::get($id);
            $this->result('查询成功', $info, 200);
        }
    }


    /**
     * 短信充值签名列表
     */
    public function sign_list()
    {
        if ($this->request->isPost()) {
            $data_list = Db::name('qt_sms_sign_log')->where('store_id', $this->userInfo['store_id'])
                ->where(['sg.store_id'=>$this->userInfo['store_id']])
                ->field('sg.*,s.name as store_name')
                ->alias('sg')
                ->leftJoin('qt_store s', 's.id = sg.store_id')
                ->order('id desc')
                ->select();
            $this->result('查询成功', $data_list, 200);
        }
    }


    //添加充值签名
    public function sign_add()
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            if (empty($data['name'])) {
                $this->result('缺少参数', '', 204);
            }
            $find = Db::name('qt_sms_sign')->where(['store_id'=>$this->userInfo['store_id']])->find();
            if(!empty($data['id'])){
                if($data['name'] == $find['name']){
                    $this->result('签名和原来一致', '', 200);
                }
                Db::name('qt_sms_sign')->where(['id'=>$data['id']])->update($data);
                $log = [
                  'sign_id'=>$data['id'],
                  'before'=>$find['name'],
                  'after'=>$data['name'],
                  'user_id'=>$this->userInfo['id'],
                  'create_time'=>time(),
                  'store_id'=>$this->userInfo['store_id'],
                ];
                Db::name('qt_sms_sign_log')->insert($log);
                $this->result('修改成功', '', 200);
            }else{
                if(!empty($find)){
                    $this->result('门店已经存在签名', '', 204);
                }
                $data['create_time'] = time();
                $insert = Db::name('qt_sms_sign')->insert($data);
                if ($insert) {
                    $this->result('新增成功', '', 200);
                } else {
                    $this->result('新增失败', '', 204);
                }
            }
        } else {
            $this->result('无效的请求', '', 204);
        }
    }

    //编辑充值签名
    public function sign_edit()
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            // 验证
            if (empty($data['name'])) {
                $this->error('请填写短信签名');
            }
            if (empty($data['id'])) {
                $this->error('缺少参数');
            }
            $before = Db::name('qt_sms_sign')->where('id', $data['id'])->find();
            $log = [
                'sign_id' => $data['id'],
                'before' => $before['name'],
                'after' => $data['name'],
                'user_id' => $this->userInfo['store_id'],
                'create_time' => time(),
            ];
            Db::name('qt_sms_sign_log')->insert($log);
            if (SmsRechargeM::update($data)) {
                $this->result('编辑成功', '', 200);
            } else {
                $this->result('编辑失败', '', 204);
            }
        } else {
            $this->result('无效的请求', '', 204);
        }
    }

    //删除充值签名
    public function sign_delete($id = null)
    {
        if ($id === null) $this->error('缺少参数');
        $re = SmsSignM::destroy($id);//
        if ($re) {
            $this->success('删除成功', 'index');
        } else {
            $this->error('系统繁忙请稍后再试', 'index');
        }

    }

    /**
     * 短信签名更改记录列表
     */
    public function sign_log()
    {
        if ($this->request->isPost()) {
            $data_list = Db::name('qt_sms_sign_log')
                ->where('sg.store_id', $this->userInfo['store_id'])
                ->field('sg.id,sg.before,sg.after,u.real_name,sg.create_time')
                ->alias('sg')
                ->leftJoin('qt_users u', 'sg.user_id = u.id')
                ->order('sg.id desc')
                ->select();
            $this->result('查询成功', $data_list, 200);
        }
    }


    /**
     * 添加短信充值签名
     */
    public function add_sms()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (empty($data['id'])) {
                $this->result('缺少参数', '', 204);
            }
            $recharge = Db::name('qt_sms_recharge')->where('id', $data['id'])->find();
            $save = [
                'store_id' => $this->userInfo['store_id'],
                'order_no' => sms_ordersn(),
                'price' => $recharge['price'],
                'number' => $recharge['number'],
                'give_number' => $recharge['give_number'],
                'pay_type' => '1',
                'content' => '',
                'create_time' => time(),
            ];
            $res = Db::name('qt_sms_recharge_log')->insert($save);
            if ($res) {
                $this->result('提交成功', '', 200);
            }
            $this->result('提交失败', '', 204);
        } else {
            $this->result('无效的请求', '', 204);
        }
    }


    /**
     * 短信服务首页
     */
    public function index()
    {
        //开通时间
        $startTime = Db::name('qt_sms_recharge_log')
            ->where(['store_id' => $this->userInfo['store_id'], 'pay_type' => '1'])
            ->order('id asc')
            ->value('create_time');
        //累计充值
        $totalMoney = Db::name('qt_sms_recharge_log')
            ->where(['store_id' => $this->userInfo['store_id'], 'pay_type' => '1'])
            ->sum('price');
        //累计条数
        $totalNumber = Db::name('qt_sms_recharge_log')
            ->where(['store_id' => $this->userInfo['store_id'], 'pay_type' => '1'])
            ->sum('number');
        //累计消费
        $consumption = Db::name('qt_sms')
            ->where(['store_id' => $this->userInfo['store_id']])
            ->count();
        $surplusNumber = $totalNumber - $consumption;
        $sign = Db::name('qt_sms_sign')->where(['store_id'=>$this->userInfo['store_id']])->find();
        $result = [
            'start_time' => $startTime,
            'total_money' => $totalMoney,
            'total_number' => $totalNumber,
            'consumption' => $consumption,
            'surplus_number' => $surplusNumber,
            'sign_name'=>$sign['name'],
            'sign_id'=>$sign['id'],
        ];
        $this->result('查询成功', $result, 200);

    }

}
